package client;

//import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
//import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

class UDPClient {
	public boolean writeDataToFile(byte[] contents,String fileName) {
		try {
			String concatFileName = "received_"+fileName;
			File file = new File(concatFileName);
			FileOutputStream fop = new FileOutputStream(file,true);
			fop.write(contents);
			fop.flush();
			fop.close();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public boolean data_sender(String SERVER_IP, int SERVER_PORT, String fileName) {
		try {

			//BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
			DatagramSocket clientSocket = new DatagramSocket();
			InetAddress IPAddress = InetAddress.getByName(SERVER_IP);
			byte[] sendData = new byte[1024];
			byte[] receiveData = new byte[24000];
			int count=0;
			//String sentence = inFromUser.readLine();
			sendData = fileName.getBytes();
			DatagramPacket sendPacket = new DatagramPacket(sendData,
					sendData.length, IPAddress, SERVER_PORT);
			clientSocket.send(sendPacket);
			DatagramPacket receivePacket = new DatagramPacket(receiveData,
					receiveData.length);
			while(true){
			
			clientSocket.receive(receivePacket);
			// Write packet to file
			//System.out.println("Received Packet");
			count++;
			System.out.println("Received "+count+" packets");
			byte[] contents = new byte[receiveData.length];
			contents = receivePacket.getData();
			
			boolean ret = writeDataToFile(contents,fileName);
			if(count == 74){
				String cmd = "mplayer received_"+fileName;
				Process p = Runtime.getRuntime().exec(cmd);
			}
			if(!ret) {
				System.err.println("Error in Writing");
				break;
			}
			}
			// String modifiedSentence = new String(receivePacket.getData());
			// System.out.println("FROM SERVER:" + modifiedSentence);
			clientSocket.close();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	
		return true;
	}
}